package com.dayu.gulimall.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author dayu
 * @version 1.0
 * @email dayu007@foxmail.com
 * @date 2021/3/20 18:19
 * @description
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping("/doLogin")
    public String login(String username, String password, String url, HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            redisTemplate.opsForValue().set(uuid,username);
            Cookie cookie = new Cookie("oss_token", uuid);
            response.addCookie(cookie);

            return "redirect:"+url+"?token="+uuid;
        }else {
         return "login";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url")String url, Model model,
                            @CookieValue(value = "oss_token",required = false) String cookie){
        if(!StringUtils.isEmpty(cookie)){
            return "redirect:"+url+"?token="+cookie;
        }
        model.addAttribute("url",url);
        return "login";
    }
}
